package com.hf.order

import grails.converters.JSON

import com.hf.bill.UserBillPeriodHistory
import com.hf.bill.UserBillPeriodHistoryService
import com.hf.date.DateUtils
import com.hf.fetch.UserFetchSummary
import com.hf.fetch.UserFetchSummaryService
import com.hf.security.OrderUser
import com.hf.security.SystemConfigService
import com.hf.security.ValidCode

class UserOrderHistoryController {

	static scaffold = UserOrderHistory

	UserOrderHistoryService userOrderHistoryService
	UserFetchSummaryService userFetchSummaryService
	SystemConfigService systemConfigService
	UserBillPeriodHistoryService userBillPeriodHistoryService
	OrderPeriodService orderPeriodService

	def userOrderPeriodHistory(long id) {
		OrderUser user
		if (id == 0) {
			user = session.user
		} else {
			user = OrderUser.get(id)
		}
		if (user) {
			List<Date> dates = DateUtils.getPeriodStartEndDay()
			OrderPeriod orderPeriod = orderPeriodService.getCurrentOrderPeriod(dates)
			List<UserOrderHistory> userOrderHistoryList = userOrderHistoryService.getUserOrderHistoryListPeriod(user, dates)

			UserBillPeriodHistory userBillPeriodHistory = userBillPeriodHistoryService.getUserBillPeriodHistory(orderPeriod, user, userOrderHistoryList.size())
			render view: '/order/user/orderPeriodHistory', model: [userOrderHistoryList : userOrderHistoryList, userBillPeriodHistory : userBillPeriodHistory]
		} else {
			forward controller: "welcome", action: "index"
		}
	}

	def monthOrderStatsHistory() {
		OrderUser user = session.user
		if (user) {
			List<Date> periodStartEndDay = DateUtils.getPeriodStartEndDay()
			int totalCount = userOrderHistoryService.getOrderMonthCount(periodStartEndDay)
			List orderMonthCountList = userOrderHistoryService.getOrderMonthCountList(periodStartEndDay)
			render view: '/order/admin/monthOrderStatsHistory', model: [orderMonthCountList : orderMonthCountList, totalCount : totalCount]
		} else {
			forward controller: "welcome", action: "index"
		}
	}
	
	def allUserPeriodStats(int intPeriod) {
		OrderUser loginUser = session.user
		if (loginUser) {
			List<Date> periodStartEndDay	= DateUtils.getPeriodStartEndDay(intPeriod)
			OrderPeriod orderPeriod = orderPeriodService.getCurrentOrderPeriod(periodStartEndDay)
			List orderUserPeriodCountList = userOrderHistoryService.getOrderUserPeriodCountList(periodStartEndDay)
	
			List<UserBillPeriodHistory> userBillPeriodHistoryList = []
			for(Object orderUserPeriodCount : orderUserPeriodCountList) {
				UserBillPeriodHistory userBillPeriodHistory = userBillPeriodHistoryService.getUserBillPeriodHistory(orderPeriod, orderUserPeriodCount[0], orderUserPeriodCount[1].intValue())
				userBillPeriodHistoryList << userBillPeriodHistory
			}

			userBillPeriodHistoryList.sort { a, b ->
					b.user.oweMoney.abs() <=> a.user.oweMoney.abs() ?:  b.totalMoney <=> a.totalMoney
			}
			
			if (intPeriod == 0) {
				intPeriod = DateUtils.getintperiodOfYear()
			}
	
			render view: '/order/admin/allUserPeriodStats', model: [userBillPeriodHistoryList : userBillPeriodHistoryList, intPeriod : intPeriod]
		} else {
			forward controller: "welcome", action: "index"
		}
	}

	def orderFromEmail(long userId, String code) {
		OrderUser user = OrderUser.get(userId)
		ValidCode validCode = ValidCode.findByEmailAndCode(user?.email, code)

		if (validCode) {
			flash.message = userOrderHistoryService.saveUserOrderHistory(user).message
			session.user = user
		} else {
			flash.message = "Sorry! Bad link."
			log.info "Bad link:  user $user.name, code $code"
		}

		render view : "/order/user/orderFromEmail"
	}

	def todayOrderedList() {
		List<OrderUser> orderedUserList = userOrderHistoryService.getOrderedUserListToay()
		List<UserFetchSummary> orderedUserFetchSummaryList = []
		if (!orderedUserList?.empty) {
			orderedUserFetchSummaryList = userFetchSummaryService.getUserFetchSummarySortList(orderedUserList)
		}
		int fetchPersonNumber = userFetchSummaryService.getFetchPersonNumber(orderedUserList.size())
		boolean isRainDay = systemConfigService.isRainDay
		List<UserFetchSummary> fetchUserList = userFetchSummaryService.getUserFetchSummaryFinalList(orderedUserFetchSummaryList, fetchPersonNumber)
		render view: "/order/user/todayOrderedList", model: [fetchUserSummaryList: orderedUserFetchSummaryList, 
			orderCount: orderedUserFetchSummaryList.size(), 
			fetchPersonNumber: fetchPersonNumber,
			 isRainDay: isRainDay,
			 fetchUserList : fetchUserList]
	}

	def todayOrderStatus() {
		OrderUser user = session.user
		if (user) {
			boolean todayOrderStatus = userOrderHistoryService.getUserOrderHistoryStatus(user)
			render view: '/order/user/todayOrderStatus', model:[todayOrderStatus : todayOrderStatus]
		} else {
			forward controller: "welcome", action: "index"
		}
	}

	// ajax
	def order() {
		OrderUser user = session.user
		Map resultMap = [:]
		if (user) {
			try {
				resultMap = userOrderHistoryService.saveUserOrderHistory(user)
			} catch(Exception e) {
			}
		} else {
			resultMap['message'] = "Please log in!"
		}
		render resultMap as JSON
	}

	// ajax
	def cancel() {
		OrderUser user = session.user
		Map resultMap = [:]
		if (user) {
			try {
				resultMap = userOrderHistoryService.deleteUserOrderHistory(user)
			} catch(Exception e) {
			}
		}  else {
			resultMap['message'] = "Please log in!"
		}
		render resultMap as JSON
	}
}
